<template>
  <el-dialog :title="formData.id?'编辑员工':'新增员工'" :visible="showDialog" @close="closeFn">
    <el-form ref="form" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" />
      </el-form-item>
      <el-form-item label="密码" :prop="formData.id?'':'password'">
        <el-input v-model="formData.password" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-row type="flex" justify="center">
        <el-button size="small" type="primary" @click="submit">确定</el-button>
        <el-button size="small" @click="closeFn">取消</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>

<script>
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateEmail = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请正确填写邮箱'))
      } else {
        if (value !== '') {
          var reg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
          if (!reg.test(value)) {
            callback(new Error('请输入有效的邮箱'))
          }
        }
        callback()
      }
    }
    return {
      formData: {
        id: '',
        username: '',
        email: '',
        provider: '',
        confirmed: '',
        blocked: '',
        image: '',
        created_at: '',
        updated_at: '',
        password: ''

      },
      rules: {
        username: [{ required: true, message: '用户名名称不能为空', trigger: 'blur' }],
        email:
         [
           { required: true, message: '邮箱不能为空', trigger: 'blur' },
           { validator: validateEmail, trigger: 'blur' }
         ],
        password: [{ required: true, message: '密码不能为空', trigger: 'blur' }]

      }
    }
  },
  methods: {
    closeFn() {
      this.$emit('update:showDialog', false)
      this.formData = {
        id: '',
        username: '',
        email: '',
        provider: '',
        confirmed: '',
        blocked: '',
        image: '',
        created_at: '',
        updated_at: '',
        password: ''
      }
      this.$refs.form.resetFields()
    },
    async submit() {
      if (this.formData.id) {
        if (this.formData.password === '') {
          this.$emit('updateNoPassword', { username: this.formData.username, email: this.formData.email })
        } else {
          this.$emit('updatePassword', { id: this.formData.id, username: this.formData.username, email: this.formData.email, password: this.formData.password })
        }
      } else {
        await this.$refs.form.validate()
        this.$emit('addEmployee', { id: this.formData.id, username: this.formData.username, email: this.formData.email, password: this.formData.password })
      }
    }
  }
}
</script>

<style>

</style>
